/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MacIndex.java
 *
 * Created on 11/07/2010, 19:15:26
 */

package net.jcdev.coolrss.view;

import com.apple.eawt.Application;
import com.explodingpixels.macwidgets.BottomBar;
import com.explodingpixels.macwidgets.BottomBarSize;
import com.explodingpixels.macwidgets.DSourceListITunes;
import com.explodingpixels.macwidgets.HudWindow;
import com.explodingpixels.macwidgets.MacIcons;
import com.explodingpixels.macwidgets.MacUtils;
import com.explodingpixels.macwidgets.MacWidgetFactory;
import com.explodingpixels.macwidgets.SourceList;
import com.explodingpixels.macwidgets.SourceListCategory;
import com.explodingpixels.macwidgets.SourceListClickListener;
import com.explodingpixels.macwidgets.SourceListControlBar;
import com.explodingpixels.macwidgets.SourceListItem;
import com.explodingpixels.macwidgets.SourceListModel;
import com.explodingpixels.macwidgets.UnifiedToolBar;
import com.explodingpixels.macwidgets.plaf.UnifiedToolbarButtonUI;
import com.explodingpixels.widgets.PopupMenuCustomizer;
import com.jgoodies.forms.layout.FormLayout;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.jcdev.coolrss.model.dao.EntryJpaController;
import net.jcdev.coolrss.model.dao.FeedJpaController;
import net.jcdev.coolrss.model.dao.TagJpaController;
import net.jcdev.coolrss.model.dao.exceptions.PreexistingEntityException;
import net.jcdev.coolrss.model.entity.Entry;
import net.jcdev.coolrss.model.entity.Feed;
import net.jcdev.coolrss.model.entity.Tag;
import thinlet.swing.app.AppFrame;
import thinlet.swing.border.LineBorder;
import thinlet.swing.container.PopupDialog;
import thinlet.swing.field.StringField;

/**
 *
 * @author carlos
 */
public class MacIndex extends AppFrame implements SourceListClickListener {

    /** Model da lista de opções. */
    private SourceListModel model;
    /** Grupo de itens para a lista de opções. */
    private SourceListCategory category;
    /** A lista de opções que receberá o modelo. */
    private SourceList sourceList;
    /** Toolbar no estilo Mac. */
    private UnifiedToolBar toolBar;
    /** Painel de feeds */
    private FeedPanel feedPanel;

    /**
     *  Creates new form BeanForm.
     */
    public MacIndex() {
        initComponents();

        UnifiedToolbarButtonUI unifiedToolbarButtonUI = new UnifiedToolbarButtonUI();


        unifiedToolbarButtonUI.installUI(btnAddFeed);
        unifiedToolbarButtonUI.installUI(btnAddTag);


        getRootPane().putClientProperty(
                "apple.awt.brushMetalLook", Boolean.TRUE);

        MacUtils.makeWindowLeopardStyle(this.getRootPane());

        toolBar = new UnifiedToolBar();

        JLabel label = new JLabel("");
        label.setSize(10, 0);
        toolBar.addComponentToLeft(label);
        toolBar.addComponentToLeft(btnAddFeed);
        toolBar.addComponentToLeft(btnAddTag);

        JTextField searchBox = new JTextField("Hello World");
        thinlet.swing.field.StringField field = new StringField(10);
        field.setWatermark("Pesquisar");

        
        searchBox.putClientProperty("JTextField.variant", "search");
        System.out.println(searchBox.getClientProperty("JTextField.variant"));
        JPanel panel = new JPanel(new FlowLayout());
        panel.add(new JLabel("Pesquisar: "));
        panel.add(searchBox);
        //toolBar.addComponentToRight(panel);
        

        toolBar.disableBackgroundPainter();
        toolBar.installWindowDraggerOnWindow(this);
        

        this.add(toolBar.getComponent(), BorderLayout.NORTH);

        BottomBar bottomBar = new BottomBar(BottomBarSize.LARGE);
        bottomBar.addComponentToCenter(MacWidgetFactory.createEmphasizedLabel("My Label"));

        this.add(bottomBar.getComponent(), BorderLayout.SOUTH);

        model = new SourceListModel();

        model = populateList(model);

        sourceList = createSourceList(model);

        feedPanel = new FeedPanel();

        splitPanel.setBorder(new LineBorder(new Color(0xaaaaaa), 1, 0, 0, 0));
        toolBar.getComponent().setBorder(new LineBorder(Color.GRAY, 0, 0, 1, 0));
        

        splitPanel.add(sourceList.getComponent(), JSplitPane.LEFT);
        splitPanel.add(feedPanel, JSplitPane.RIGHT);

        //SwingUtilities.updateComponentTreeUI(this);
    }

    /**
     * Create new Source List.
     * @param modelAux A list model
     * @return New Source List
     */
    public final SourceList createSourceList(final SourceListModel modelAux) {
        SourceList sourceListAux = new SourceList(modelAux);

        SourceListControlBar controlBar = new SourceListControlBar();
        sourceListAux.installSourceListControlBar(controlBar);
        controlBar.installDraggableWidgetOnSplitPane(splitPanel);

        controlBar.createAndAddPopdownButton(MacIcons.GEAR,
         new PopupMenuCustomizer() {
            @Override
             public void customizePopup(final JPopupMenu popup) {
                 popup.removeAll();
                 popup.add(new JMenuItem("Item One"));
                 popup.add(new JMenuItem("Item Two"));
                 popup.add(new JMenuItem("Item Three"));
             }
         });

         sourceListAux.getComponent().setBorder(new LineBorder(Color.GRAY, 0, 0, 0, 1));

         sourceListAux.addSourceListClickListener(this);

         return sourceListAux;
    }

    /**
     * Popula a lista com os feeds existentes.
     * @return A lista de feeds
     */
    public final SourceListModel populateList(SourceListModel model) {

        TagJpaController tjc = new TagJpaController();
        int tagCount = tjc.getTagCount();

        List<Tag> tags;

        if (tagCount > 0) {
            tags = tjc.findTagEntities();

            for (Tag t : tags) {

                SourceListCategory cat = new SourceListCategory(
                        t.getTagName());
                model.addCategory(cat);
                

                List<Feed> feeds = t.getFeedList();
                for (Feed f : feeds) {
                    SourceListItem sli = new SourceListItem(f.getFeedTitle());
                    sli.setCounterValue(f.getEntryList().size());
                    model.addItemToCategory(sli, cat);
                }
            }
        }

        return model;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnAddFeed = new javax.swing.JButton();
        btnAddTag = new javax.swing.JButton();
        btnRefresh = new javax.swing.JButton();
        splitPanel = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        btnAddFeed.setIcon(new javax.swing.ImageIcon(getClass().getResource("/net/jcdev/coolrss/resources/feed_add.png"))); // NOI18N
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("net/jcdev/coolrss/resources/index"); // NOI18N
        btnAddFeed.setText(bundle.getString("toolbar.add_feed")); // NOI18N
        btnAddFeed.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddFeedActionPerformed(evt);
            }
        });

        btnAddTag.setIcon(new javax.swing.ImageIcon(getClass().getResource("/net/jcdev/coolrss/resources/rss32.png"))); // NOI18N
        btnAddTag.setText(bundle.getString("toolbar.add_tag")); // NOI18N

        btnRefresh.setText("jButton1");

        splitPanel.setBorder(null);
        splitPanel.setDividerLocation(200);
        splitPanel.setDividerSize(0);
        splitPanel.setRightComponent(jPanel1);

        getContentPane().add(splitPanel, java.awt.BorderLayout.CENTER);

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);
    }// </editor-fold>//GEN-END:initComponents

    private void btnAddFeedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddFeedActionPerformed

        try {

            // Obtendo a URL do feed com o usuário
            String feedURL = JOptionPane.showInputDialog(
                    this,
                    "Enter feed URL:",
                    "Add new feed",
                    JOptionPane.QUESTION_MESSAGE);

            // Recuperando o feed
            SyndFeedInput input = new SyndFeedInput();
            SyndFeed syndFeed = input.build(new XmlReader(new URL(feedURL)));

            // Criando as entidades
            Feed feed = new Feed();

            feed.setFeedLink(feedURL);
            feed.setFeedTitle(syndFeed.getTitle());
            feed.setFeedPublishedDate(syndFeed.getPublishedDate());
            feed.setFeedDescription(syndFeed.getDescription());

            TagJpaController tjc = new TagJpaController();
            Tag uTag = tjc.findTag("UNCATEGORIZED");

            feed.setTagName(uTag);

            // Criando a lista de entradas
            List<Entry> entries = new ArrayList<Entry>();

            List<SyndEntryImpl> syndEntries =
                    (List<SyndEntryImpl>) syndFeed.getEntries();

            EntryJpaController ejc = new EntryJpaController();

            for (SyndEntryImpl syndEntry : syndEntries) {
                Entry entry = new Entry();

                entry.setEntryLink(syndEntry.getLink());
                entry.setEntryAuthor(syndEntry.getAuthor());
                entry.setEntryTitle(syndEntry.getTitle());
                entry.setEntryPublishedDate(syndEntry.getPublishedDate());
                entry.setEntryUpdatedDate(syndEntry.getUpdatedDate());
                entry.setEntryStatus('U');
                entry.setEntryDescription(syndEntry.getDescription().getValue());
                entry.setFeedLink(feed);

                entries.add(entry);

                System.out.println(syndEntry.getTitle());
            }

            feed.setEntryList(entries);
            feed.setEntryList(null);

            // Armazenando os dados do Feed no banco de dados.
            FeedJpaController fjc = new FeedJpaController();
            try {
                fjc.create(feed);

                for (int i = 0; i < entries.size(); i++) {
                    ejc.create(entries.get(i));
                }
                
                SourceListModel modelAux = new SourceListModel();

                modelAux = populateList(modelAux);

                sourceList = createSourceList(modelAux);

                splitPanel.add(sourceList.getComponent(), JSplitPane.LEFT);
                splitPanel.setDividerLocation(250);

            } catch (PreexistingEntityException ex) {
                Logger.getLogger(MacIndex.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(MacIndex.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        } catch (IOException ex) {
            Logger.getLogger(MacIndex.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(MacIndex.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FeedException ex) {
            Logger.getLogger(MacIndex.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_btnAddFeedActionPerformed

    @Override
    protected void init() {

    }

    @Override
    protected boolean close() {
        return true;
    }

    /**
     * Cria uma nova janela com o tamanho especificado.
     * @param width A largura da janela.
     * @param height A altura da janela.
     */
    public final void showMacFrame(final int width, final int height) {
        super.showFrame(width, height);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddFeed;
    private javax.swing.JButton btnAddTag;
    private javax.swing.JButton btnRefresh;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSplitPane splitPanel;
    // End of variables declaration//GEN-END:variables

    @Override
    public void sourceListItemClicked(SourceListItem sli, Button button, int i) {
        String name = sli.getText();
        FeedJpaController fjc = new FeedJpaController();
        Feed feed = fjc.findFeedByTitle(name);
        
        feedPanel.populateTable(feed);

        splitPanel.add(feedPanel, JSplitPane.RIGHT);

    }

    @Override
    public void sourceListCategoryClicked(SourceListCategory slc, Button button, int i) {
        //System.out.println("Clicked");
        System.out.println(slc.getItemCount() + " itens");
    }

}
